/*
 *  Copyright 2015-2016, RenGu Technology (BeiJing) Co., Ltd.
 *  All right reserved.
 *
 *  THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF RENGU TECHNOLOGY (BeiJing) CO., LTD.
 *
 *  THE CONTENTS OF THIS FILE MAY NOT BE DISCLOSED TO THIR PARTIES,
 *  COPIED OR DUPLICATED IN ANY FORM, IN WHOLE OR IN PART,
 *  WITHOUT THE PRIOR WRITTEN PERMISSION OF RENGU TECHNOLOGY (BeiJing) CO., LTD.
 *
 *  VirtAcctPreAuth
 *
 *  Edit History:
 *      lizhangtao Created on 2020年04月12日
 *
 */
package cc.rengu.igas.acct.core.service.trans;

import cc.rengu.igas.acct.common.dao.AcctDetailMapper;
import cc.rengu.igas.acct.common.dao.MapperCommon;
import cc.rengu.igas.acct.common.dao.impl.AcctDetailMapperImpl;
import cc.rengu.igas.acct.common.entity.AcctDetail;
import cc.rengu.igas.acct.common.enums.AcctRespCodeEnum;
import cc.rengu.igas.acct.common.enums.AcctTransStatusEnum;
import cc.rengu.igas.acct.core.service.realize.AcctOpt;
import cc.rengu.igas.acct.facade.request.VirtAcctPreAuthCompRequest;
import cc.rengu.igas.acct.facade.response.VirtAcctPreAuthCompResponse;
import cc.rengu.oltp.service.base.RadpService;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.common.enums.TransStatusEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.DbsUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import cc.rengu.utility.base.StringUtil;
import com.alibaba.fastjson.JSONObject;

import java.util.Optional;

/**
 * 预授权完成
 * 扣减账户余额、
 * 扣减冻结余额中交易时冻结的金额
 *
 * @author lizhangtao
 * @version 1.0
 * @date 2020/5/8
 */
public class VirtAcctPreAuthCompleteService extends RadpService {

    @Override
    protected int bizInit(String s) {
        return 0;
    }

    @Override
    protected int bizProcess(String s, int i) {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        VirtAcctPreAuthCompRequest virtAcctPreAuthCompRequest = new VirtAcctPreAuthCompRequest();
        VirtAcctPreAuthCompResponse virtAcctPreAuthCompResponse = new VirtAcctPreAuthCompResponse();
        try {

            ConvertUtil.convertOutput(virtAcctPreAuthCompRequest);
            rglog.info("virtAcctPreAuthCompRequest = <{}>", JSONObject.toJSONString(virtAcctPreAuthCompRequest));

            virtAcctPreAuthCompResponse.setHeader(virtAcctPreAuthCompRequest.getHeader());
            BizResponse<VirtAcctPreAuthCompResponse> bizResponse = new BizResponse<>();
            bizResponse.setResult(virtAcctPreAuthCompResponse);
            //解冻并借记操作
            AcctDetail acctDetail = new AcctOpt().freezeComplete(virtAcctPreAuthCompRequest.getHeader().getTransDate(),
                    virtAcctPreAuthCompRequest.getHeader().getTransTime(), virtAcctPreAuthCompRequest.getHeader().getTxnNum(),
                    virtAcctPreAuthCompRequest.getHeader().getSrcSysId(), virtAcctPreAuthCompRequest.getHeader().getInstId(),
                    virtAcctPreAuthCompRequest.getHeader().getTraceNo(), virtAcctPreAuthCompRequest.getFreezeAcctSeqNum(),
                    virtAcctPreAuthCompRequest.getTransAmt(), virtAcctPreAuthCompRequest.getAcctNo(),
                    virtAcctPreAuthCompRequest.getCustomerId(), virtAcctPreAuthCompRequest.getUserType(),
                    virtAcctPreAuthCompRequest.getUserId(), virtAcctPreAuthCompRequest.getSummary(), rglog);

            virtAcctPreAuthCompResponse.setAfterBalance(acctDetail.getAfterBalance());
            virtAcctPreAuthCompResponse.setAfterAvailableBalance(acctDetail.getAfterAvailableBalance());
            virtAcctPreAuthCompResponse.setAfterFreezeBalance(acctDetail.getAfterFreezeBalance());
            virtAcctPreAuthCompResponse.setAcctDate(acctDetail.getAcctDate());
            virtAcctPreAuthCompResponse.setAcctSeqNum(acctDetail.getAcctSeqNum());
            virtAcctPreAuthCompResponse.setRespCode(OltpRpcdEnum.TRANS_SUCCESS.getRespCode());
            virtAcctPreAuthCompResponse.setRespDesc(OltpRpcdEnum.TRANS_SUCCESS.getRespDesc());
            virtAcctPreAuthCompResponse.setTransStatus(AcctTransStatusEnum.SUCC.getStatus());
            bizResponse.setRspSysId(ChannelEnum.ACCT.getChannelType());
            bizResponse.setTransStatus(TransStatusEnum.TRANS_SUCC);
            bizResponse.setRespCode(OltpRpcdEnum.TRANS_SUCCESS.getRespCode());
            bizResponse.setRespDesc(OltpRpcdEnum.TRANS_SUCCESS.getRespDesc());
            ConvertUtil.convertInput(bizResponse.getResult());

        } catch (BizException e) {
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, e.getCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, e.getMessage());
                if (AcctRespCodeEnum.ORIG_TRANS_COMPLETE_ERROR.getRespCode().equals(e.getCode())) {
                    //查询并返回预授权完成流水
                    String dbPoolName = MapperCommon.getDbPoolName();
                    DbsUtil dbsUtil = new DbsUtil(dbPoolName);
                    AcctDetailMapper acctDetailMapper = new AcctDetailMapperImpl();
                    Optional<AcctDetail> acctDetailOpt = acctDetailMapper.fetchListByOrigAcctSeqNum(virtAcctPreAuthCompRequest.getHeader().getInstId(), virtAcctPreAuthCompRequest.getFreezeAcctSeqNum(),
                            virtAcctPreAuthCompRequest.getAcctNo(), virtAcctPreAuthCompRequest.getCustomerId(), virtAcctPreAuthCompRequest.getUserType(),
                            virtAcctPreAuthCompRequest.getUserId()).stream().filter(item -> "D".equals(item.getDebitCreditFlag())).filter(item -> "00".equals(item.getAcctStatus())).findFirst();
                    AcctDetail acctDetail = null;
                    if (acctDetailOpt.isPresent()) {
                        acctDetail = acctDetailOpt.get();
                        rglog.debug("acctDetail = <{}>", JSONObject.toJSONString(acctDetail));
                        virtAcctPreAuthCompResponse.setAcctSeqNum(acctDetail.getAcctSeqNum());
                    }
                    //赋值
                    ConvertUtil.convertInput(virtAcctPreAuthCompResponse);
                }
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e1));
            }
        } catch (Exception e) {
            rglog.error(StringUtil.ExceptionToString(e));
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE,
                        OltpRpcdEnum.BIZ_PROCESS_TIMEOUT.getRespCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC,
                        OltpRpcdEnum.BIZ_PROCESS_TIMEOUT.getRespDesc());
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e));
            }
        }
        return 0;
    }

    @Override
    protected int bizTerminate(String s) {
        return 0;
    }

}
